package com.wf.course.web.controller.comm;

import com.utils.page.PageBean;
import com.wf.course.model.ad.IndexType;
import com.wf.course.model.ad.VipCard;
import com.wf.course.model.comm.Distribution;
import com.wf.course.model.course.CourseInfo;
import com.wf.course.service.ICourseInfoService;
import com.wf.course.service.IDistributionService;
import com.wf.course.service.IVipCardService;
import com.wf.course.web.Interceptor.LogInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @Auther: liu
 * @Date: 2018/7/13 14:43
 * @Description: 分销管理
 */
@Controller
@RequestMapping("distribution")
public class DistributionController {

    private static Logger logger = LoggerFactory.getLogger(DistributionController.class);

    @Autowired
    private IDistributionService distributionService;

    @Autowired
    private ICourseInfoService courseInfoService;

    @Autowired
    private IVipCardService vipCardService;

    @RequestMapping("configuration")
    public ModelAndView configuration(ModelAndView mav) {
        mav.addObject("page", distributionService.configuration());
        mav.setViewName("comm/distributionConfiguration");
        return mav;
    }

    @RequestMapping("configure")
    public String configure(Distribution distribution) {
        distributionService.configure(distribution);
        return "redirect:/distribution/configuration";
    }

    /**
     * 推广记录
     *
     * @param pageNo
     * @param pageSize
     * @param distribution
     * @param mav
     * @return
     */
    @RequestMapping("record")
    public ModelAndView record(Integer pageNo, Integer pageSize, Distribution distribution, ModelAndView mav) {
        try {
            PageBean<Distribution> pageBean = new PageBean<>(pageNo, pageSize);
            pageBean.setObj(distribution);
            pageBean.setUrl("distribution/record");
            distributionService.record(pageBean);
            StringBuilder builder = new StringBuilder();
            for (Field f : distribution.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(distribution) && StringUtils.isNotBlank(f.get(distribution).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(distribution));
                }
            }
            pageBean.setParams(builder.toString());
            mav.addObject("page", pageBean);
            mav.setViewName("comm/distributionRecord");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return mav;
    }

    /**
     * 参加优惠的课程列表
     *
     * @param pageNo
     * @param pageSize
     * @param distribution
     * @param mav
     * @return
     */
    @RequestMapping("goodsList")
    public ModelAndView goodsList(Integer pageNo, Integer pageSize, Distribution distribution, ModelAndView mav) {
        try {
            PageBean<Distribution> pageBean = new PageBean<>(pageNo, pageSize);
            pageBean.setObj(distribution);
            pageBean.setUrl("distribution/goodsList");
            distributionService.goodsList(pageBean);
            StringBuilder builder = new StringBuilder();
            for (Field f : distribution.getClass().getDeclaredFields()) {
                f.setAccessible(true);
                if (null != f.get(distribution) && StringUtils.isNotBlank(f.get(distribution).toString())) {
                    builder.append("&" + f.getName() + "=" + f.get(distribution));
                }
            }
            pageBean.setParams(builder.toString());
            mav.addObject("page", pageBean);
            mav.setViewName("comm/distributionGoodsList");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return mav;
    }


    /**
     * 修改页面数据初始化
     * @param id
     * @param model
     * @return
     */
    @LogInfo("新增或修改首页分类，页面数据初始化")
    @RequestMapping("pageLoad/{id}")
    public String downLoadById(@PathVariable("id") Integer id, Model model) {

        if (id != null && id != 0) {
            List<CourseInfo> courses = courseInfoService.queryCourses();
            model.addAttribute("courses", courses);
            List<VipCard> cards = vipCardService.queryVipCards();
            model.addAttribute("cards", cards);
            Distribution distribution = distributionService.getGoodById(id);
            model.addAttribute("distribution", distribution);
            model.addAttribute("type", "upd");
        }else{
            model.addAttribute("type", "add");
        }

        return "comm/distributionGoodsEdit";
    }

    /**
     * 新增和修改
     * @param distribution
     * @param request
     * @return
     */
    @LogInfo("新增或修改首页分类")
    @RequestMapping(value = "distributionGoodsEdit" , produces = "text/html;charset=UTF-8")
    public String distributionGoodsEdit(@ModelAttribute Distribution distribution, HttpServletRequest request) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.isNotBlank(distribution.getRangeTime())) {
            String[] date = distribution.getRangeTime().split(" - ");
            distribution.setBeginTime((int)(format.parse(date[0]).getTime()));
            distribution.setEndTime((int)(format.parse(date[1]).getTime()));
        }

        distributionService.saveOrUpdateDistribution(distribution);

        return "redirect:/distribution/goodsList";
    }

    @RequestMapping("deleteGoods/{id}")
    public String deleteGoods(@PathVariable("id") Integer id) {
        distributionService.deleteGoods(id);
        return "redirect:/distribution/goodsList";
    }

    @RequestMapping("addGoods")
    public String addGoods(Distribution distribution) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Long time = System.currentTimeMillis() / 1000;
            distribution.setCreateTime(time.intValue());
            distribution.setUpdateTime(time.intValue());
            if (StringUtils.isNotBlank(distribution.getRangeTime())) {
                String[] rangeTime = distribution.getRangeTime().split(" - ");
                distribution.setBeginTime(((Long) (format.parse(rangeTime[0]).getTime() / 1000)).intValue());
                distribution.setEndTime(((Long) (format.parse(rangeTime[1]).getTime() / 1000)).intValue());
            }
            distribution.setGoodsId(distribution.getGoodsSort().equals(1) ? distribution.getCourseId() : distribution.getCardId());
            distributionService.addGoods(distribution);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return "redirect:/distribution/goodsList";
    }

    @RequestMapping("toAddGoods")
    public String toAddGoods(Model model) {
        List<CourseInfo> courses = courseInfoService.queryCourses();
        model.addAttribute("courses", courses);
        List<VipCard> cards = vipCardService.queryVipCards();
        model.addAttribute("cards", cards);
        return "comm/distributionAddGoods";
    }
}
